package com.sinaapp.gavinzhang.fifth;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * 带有序检测的二分查找
 * Created by gavin on 15-8-8.
 */
public class BinarySearchWithCheck {
    @Test
    public void twoSearchTest()
    {
        int[] numbers = {0,1,2,3,4,5,6,7,8,9,10,11};
        for (int i = -10; i < 17 ; i++) {
            if (i>=0 && i< numbers.length)
            {
                assertEquals(twoSearch(numbers,i),"find"+i);
            }
            else {
                assertEquals(twoSearch(numbers,i),"not find");
            }
        }
    }

    public String twoSearch(int[] numbers,int t)
    {
        //int[] numbers = {0,1,2,3,4,5,6,7,8,9,10,11};

        //检测
        for (int i = 0; i < numbers.length; i++) {
            if (i+1 < numbers.length)
            {
                if (numbers[i] > numbers[i+1])return "check error";
            }
        }


        int start = 0;
        int stop = numbers.length-1;
        //int t = 3;
        while (start<=stop)
        {
            int middle = (start+start)/2;
            if (numbers[middle] == t)
            {
                return  "find"+middle;
            }else if (numbers[middle] > t){
                stop = middle-1;
            }else {
                start = middle+1;
            }
        }
        if (start>stop)
        {
            return "not find";
        }
        return "errors";
    }
}
